import { Component, OnInit } from '@angular/core';
import { GridOptions } from '@ag-grid-community/core';
import { ExportExcelService } from '@core/services/excel/export-excel.service';
import { GridConfigService } from '@core/config/grid-config.service';
import { ApesMessageService } from '@shared/apes/message';
import { UserAuthService } from '@core/services/user-auth.service';
import { ApiService } from '@core/services/http/api.service';
import { Router } from '@angular/router';
import { DatePipe } from '@angular/common';
import * as CryptoJS from 'crypto-js';
import { BiService } from '../../../bi.service';


@Component({
  selector: 'sheet-metal-daily',
  templateUrl: './sheet-metal-daily.component.html',
  styleUrls: ['../../door-tube-center-all.scss'],
})
export class SheetMetalDailyComponent implements OnInit {
  height: any = window.innerHeight - 200 + 'px';
  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  getContextMenuItems: any;

  userInfo = this.userAuthService.getUserInfoObj();
  companyId = this.userInfo.userAccount.post.company.id;
  companyList: any;

  /** 按钮相关 */
  buttonBar = [{ hide: true, style: 'default', label: '刷新', id: 'action_query', loading: false },
    { hide: true, style: 'default', label: '导出', id: 'action_export', api: '', loading: false }];
  title = '';
  ctx = { model: {} };
  JCJDID: string;

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private router: Router,
              private exportExcelService: ExportExcelService,
              private msg: ApesMessageService,
              private userAuthService: UserAuthService,
              private datePipe: DatePipe,
              private bi: BiService) {
    // this.companyList = [];
    // this.companyList.push(this.companyId);

    this.columnDefs = [
      { 'headerName': '基地', field: 'MDMC' },
      { 'headerName': '基地留存', field: 'JDLC' },
      { 'headerName': '今日接车', field: 'JRJC' },
      { 'headerName': '待接车', field: 'DJC' },
      { 'headerName': '今日预计交车', field: 'YJJRJC' },
      { 'headerName': '今日门店实际收车', field: 'JRSJJC' },
      { 'headerName': '交车幅数', field: 'JCFS' },
      { 'headerName': '月累计交车', field: 'YLJJC' },
      { 'headerName': '月累计交车幅数', field: 'YLJFS' },
      { 'headerName': '基地归还超时', field: 'JDGHCS' },
      { 'headerName': '定损中', field: 'DSZ' },
      { 'headerName': '制定服务方案', field: 'ZDFWFA' },
      { 'headerName': '待施工', field: 'DSG' },
      { 'headerName': '施工中', field: 'SGZ' },
      { 'headerName': '施工暂停', field: 'SGZT' },
      { 'headerName': '已完成', field: 'SGWC' },
      { 'headerName': '明日预计交车', field: 'YJMRJC' },
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 100,
      rowHeight: 35,
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.getContextMenuItems = (params) => {
      const result = [
        'copy',
        'separator',
        { name: params.value },
        'separator',
        {
          name: '查看详情',
          action: () => {
            this.send(params);
          },
        },
      ];
      return result;
    };

  }

  ngOnInit() {
    if (this.userInfo.userAccount.post.dept) {
      this.JCJDID = this.userInfo.userAccount.post.dept.id;
    }
    this.bi.getCompany(this.userInfo.userAccount.post.localPermit.id).then(value => {
      // @ts-ignore
      this.companyList = value.map((item)=>{
        return item.id;
      });
    });
    this.getTablesData();
  }

  getTablesData() {
    const data = {
      'interfaceMethod': 'ipmBPforAppService.qryJDBPBB', 'pdata': { 'companyId': this.companyList, 'MDID': this.JCJDID },
    };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            const list = JSON.parse(result.obj);
            this.rowData = list;
            if (this.rowData.length === 0) {
              this.msg.info(`未找到满足条件的数据`);
            }
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  send(params: any) {
    let list = {};
    const baseId = params.node.data['MDID'];  // 基地id
    let currentId = params.column.colId;     // 判断当前列
    let retain;                             // 基地留存（是否交车为否）
    let jdStartTime = null;                   // 基地接车开始时间
    let jdEndTime = null;                     // 基地接车结束时间
    let yjStartTime = null;                   // 预计交车开始时间
    let yjEndTime = null;                     // 预计交车结束时间
    let sjStartTime = null;                   // 交车开始时间
    let sjEndTime = null;                     // 交车结束时间
    let key;                                   // 车辆状态

    if (currentId !== 'MDMC' && currentId !== 'DJC' && currentId !== 'JCFS' && currentId !== 'YLJFS') {
      switch (currentId) {
        case 'JDLC':
          retain = 0;
          break;
        case 'JRJC':
          jdStartTime = this.timeChange(new Date().getTime());
          jdEndTime = this.timeChange(new Date().getTime());
          break;
        case 'YJJRJC':
          yjStartTime = this.timeChange(new Date().getTime());
          yjEndTime = this.timeChange(new Date().getTime());
          break;
        case 'JRSJJC':
          sjStartTime = this.timeChange(new Date().getTime());
          sjEndTime = this.timeChange(new Date().getTime());
          break;
        case 'JDGHCS':
          yjStartTime = this.timeChange(new Date().getTime() - (61 * 24 * 60 * 60 * 1000));
          yjEndTime = this.timeChange(new Date().getTime() - (1 * 24 * 60 * 60 * 1000));
          break;
        case 'YLJJC':
          const days = new Date().getDate();
          sjStartTime = this.timeChange(new Date().getTime() - ((days - 1) * 24 * 60 * 60 * 1000));
          sjEndTime = this.timeChange(new Date().getTime());
          break;
        case 'YJMRJC':
          yjStartTime = this.timeChange(new Date().getTime() + (1 * 24 * 60 * 60 * 1000));
          yjEndTime = this.timeChange(new Date().getTime() + (1 * 24 * 60 * 60 * 1000));
          break;
        case 'DSZ':
          key = 'DSZ';
          break;
        case 'ZDFWFA':
          key = 'ZDFWFA';
          break;
        case 'DSG':
          key = 'DSG';
          break;
        case 'SGZ':
          key = 'SGZ';
          break;
        case 'SGZT':
          key = 'SGZT';
          break;
        case 'SGWC':
          key = 'SGWC';
          break;
      }

      list = {
        'interfaceMethod': 'ipmBPforAppService.getBPLBData', 'pdata': {
          'tjJson': {
            'JCJDID': baseId, 'companyId': this.companyList,
            'JDJCRQ_SJ_KS': jdStartTime, 'JDJCRQ_SJ_JS': jdEndTime,
            'YJJCRQ_SJ_KS': yjStartTime, 'YJJCRQ_SJ_JS': yjEndTime,
            'JCRQ_SJ_KS': sjStartTime, 'JCRQ_SJ_JS': sjEndTime,
            'SFYJC': retain, 'CLZT': key,
          },
        },
      };

      let value = CryptoJS.enc.Utf8.parse(JSON.stringify(list));
      value = CryptoJS.enc.Base64.stringify(value);
      this.router.navigate(['/bi/door-tube-center/sheetMetalCount'], { queryParams: { value: value } });


    }


  }

  timeChange(time: number) {
    let day;
    if (time !== undefined) {
      day = this.datePipe.transform(new Date(time),
        'yyyy-MM-dd');
      return day;
    }
  }

  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.queryData();
      } else if (data.id === 'action_export') {
        this.action_export();
      }
    }
  }

  queryData() {
    this.getTablesData();
    this.buttonBar[0].loading = false;
  }

  /**
   * 功能：导出Grid数据
   */
  action_export() {
    if (this.rowData && this.rowData.length === 0) {
      return;
    }
    const columnList = this.gridOptions.columnDefs;
    this.exportExcelService.exportWithDealData(columnList, this.rowData, '基地每日服务统计');
  }

}
